package fsdownloadserver;

import com.thoughtworks.xstream.*;
import com.thoughtworks.xstream.io.xml.DomDriver;
import java.io.*;
import java.util.ArrayList;

/**
 * @author
 */
public class ServerInfoLoader {
    private XStream xstream;

    public ServerInfoLoader(){
        xstream = new XStream(new DomDriver());
        xstream.alias("ServerInfo", ServerInfo.class);
        xstream.alias("ServerList", ArrayList.class);
    }

    public ArrayList<ServerInfo> LoadInfo(String path){
        System.out.println("Loading information about fileservers");
        try{
            FileInputStream istream = new FileInputStream(path);
            ArrayList<ServerInfo> tempServerInfoList = (ArrayList<ServerInfo>) xstream.fromXML(istream);
            for(ServerInfo serverInfo:tempServerInfoList){
                System.out.println("-> "+serverInfo.getName()+" from: "+serverInfo.getUrl()+":"+serverInfo.getPort());
            }
            return tempServerInfoList;
        }
        catch(Exception ex){
            ex.printStackTrace();
            System.exit(1);
        }
        return null;
    }

    public void SaveInfo(String path, ArrayList<ServerInfo> infoList){
        try{
            FileOutputStream ostream = new FileOutputStream(path);
            xstream.toXML(infoList,ostream);
        }
        catch(Exception ex){
            ex.printStackTrace();
            System.exit(2);
        }
    }
}

